package com.example.osixaffairssystem.controller;

import com.example.osixaffairssystem.domain.PageBean;
import com.example.osixaffairssystem.domain.Result;
import com.example.osixaffairssystem.domain.model.Class;
import com.example.osixaffairssystem.service.ClassService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/class")
@RequiredArgsConstructor
public class ClassController {

    final ClassService classService;

    @GetMapping("/list")
    public Result list() {
        log.info("获取班级列表");
        List<Class> list = classService.list();
        return Result.success(list);
    }

    @GetMapping
    public Result listToPage(@RequestParam() Integer page, @RequestParam() Integer pageSize) {
        log.info("分页查询班级{ page: {}, pageSize: {} }", page, pageSize);
        PageBean<Class> list = classService.listToPage(page, pageSize);
        return Result.success(list);
    }

    @PostMapping
    public Result insert(@RequestBody Class clazz) {
        log.info("新增班级: {}",clazz);
        Integer id = null;
        try {
            id = classService.insert(clazz);
        } catch (DuplicateKeyException e) {
            return new Result(HttpStatus.CONFLICT.value(), "Duplicate_Key", null);
        }
        return Result.success(id);
    }

    @PutMapping
    public Result update(@RequestBody Class clazz) {
        log.info("修改班级: {}",clazz);
        classService.update(clazz);
        return Result.success();
    }

    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable List<Integer> ids) {
        log.info("删除班级: {}",ids);
        classService.delete(ids);
        return Result.success();
    }

}
